import React, { PureComponent, Fragment } from 'react';
import {
  Form,
  Input,
  Select,
  Modal,
  Radio, Upload, Button, Icon,
} from 'antd';
import { phone, email } from '@/utils/regular';
import { connect } from 'dva';

const FormItem = Form.Item;
const { TextArea } = Input;

const RadioGroup = Radio.Group;

@connect(({ packing }) => ({
  packing,
}))
@Form.create()
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
    this.state = {
      logoList: [],
      iconList: [],
      introduceList: [],
    };
  }


  onRemoveLogo = (e) => {
    const { logoList } = this.state;
    console.log(logoList);
    let dataArr = JSON.parse(JSON.stringify(logoList));
    dataArr.map((item, index) => {
      if (item.uid === e.uid) {
        dataArr.splice(index, 1);
      }
    });
    this.setState({
      logoList: dataArr,
    });
  };
  onRemoveIntroduce = (e) => {
    const { introduceList } = this.state;
    let dataArr = JSON.parse(JSON.stringify(introduceList));
    dataArr.map((item, index) => {
      if (item.uid === e.uid) {
        dataArr.splice(index, 1);
      }
    });
    this.setState({
      introduceList: dataArr,
    });
  };
  onRemoveIcon = (e) => {
    const { iconList } = this.state;
    let dataArr = JSON.parse(JSON.stringify(iconList));
    dataArr.map((item, index) => {
      if (item.uid === e.uid) {
        dataArr.splice(index, 1);
      }
    });
    this.setState({
      iconList: dataArr,
    });
  };
  handleChange = (type, info) => {
    let logoList = info;
    logoList = logoList.map((file) => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });

    logoList = logoList.filter((file) => {
      if (file.response) {
        return file.response.status === 'success';
      }
      return true;
    });
    if (type === 'logo') {
      this.setState({ logoList });
    } else if (type === 'introduce') {
      this.setState({ introduceList: logoList });
    } else {
      this.setState({ iconList: logoList });
    }
  };
  iconCustomRequest = (componentsData) => {
    let _this = this;
    const { dispatch, form } = this.props;
    let originFile = componentsData.file;
    const formData = new FormData();
    formData.append('multipartFile', originFile);
    formData.append('name', originFile.name);
    formData.append('uid', originFile.uid);
    dispatch({
      type: 'global/upload',
      payload: formData,
      callback(res) {
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          form.setFieldsValue({
            brandIcon: res.msg.url,
          });
          _this.handleChange('icon', [obj]);
        }
      },
    });
  };
  introduceRequest = (componentsData) => {
    let _this = this;
    const { dispatch, form } = this.props;
    let originFile = componentsData.file;
    const formData = new FormData();
    formData.append('multipartFile', originFile);
    formData.append('name', originFile.name);
    formData.append('uid', originFile.uid);
    dispatch({
      type: 'global/upload',
      payload: formData,
      callback(res) {
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          form.setFieldsValue({
            introduce: res.msg.url,
          });
          _this.handleChange('introduce', [obj]);
        }
      },
    });
  };
  customRequest = (componentsData) => {
    let _this = this;
    const { dispatch, form } = this.props;
    let originFile = componentsData.file;
    const formData = new FormData();
    formData.append('multipartFile', originFile);
    formData.append('name', originFile.name);
    formData.append('uid', originFile.uid);
    dispatch({
      type: 'global/upload',
      payload: formData,
      callback(res) {
        const keys = form.getFieldValue('brandLogo');
        console.log(123, keys);
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          form.setFieldsValue({
            brandLogo: res.msg.url,
          });
          _this.handleChange('logo', [obj]);
        }
      },
    });


  };

  // 表单
  renderContent = () => {
    const { form, values } = this.props;
    const { logoList, iconList, introduceList } = this.state;
    const logoProps = {
      action: `/img/upload`,
      showUploadList: { showPreviewIcon: true, showRemoveIcon: false },
      multiple: false,
      customRequest: this.customRequest,
      listType: 'picture-card',
      className: 'upload-list-inline',
    };

    const introduceProps = {
      action: `/img/upload`,
      showUploadList: { showPreviewIcon: true, showRemoveIcon: false },
      multiple: false,
      customRequest: this.introduceRequest,
      listType: 'picture-card',
      className: 'upload-list-inline',
    };
    return [
      <FormItem key="brandName" {...this.formLayout} label="品牌名称">
        {form.getFieldDecorator('brandName', {
          rules: [{ required: true, message: '请输入品牌名称！' }],
          initialValue: values.brandName,
        })(<Input placeholder="请输入"/>)}
      </FormItem>,
      <FormItem key="brandLogo" {...this.formLayout} label="LOGO">
        {logoList.length > 0 ? form.getFieldDecorator('brandLogo', {
            rules: [{ required: true, message: '请上传品牌logo！' }],
            initialValue: values.brandLogo,
          })(<Upload {...logoProps} fileList={logoList}>
            LOGO<Icon type="upload"/>上传
          </Upload>) :
          form.getFieldDecorator('brandLogo', {
            rules: [{ required: true, message: '请上传品牌logo！' }],
            initialValue: values.brandLogo,
          })(<Upload {...logoProps} fileList={
            values.brandLogo ? [
              {
                name: values.brandLogo,
                uid: 1,
                url: values.brandLogo,
              },
            ] : []
          }>
            LOGO<Icon type="upload"/>上传
          </Upload>)}
      </FormItem>,

      <FormItem key="status" {...this.formLayout} label="状态">
        {form.getFieldDecorator('status', {
          rules: [{ required: true, message: '请选择状态！' }],
          initialValue: values.status,
        })(
          <RadioGroup>
            <Radio value={1}>启用</Radio>
            <Radio value={2}>暂停</Radio>
          </RadioGroup>,
        )}
      </FormItem>,
      <FormItem key="flag" {...this.formLayout} label="优质">
        {form.getFieldDecorator('flag', {
          rules: [{ required: true, message: '请选择状态！' }],
          initialValue: values.flag,
        })(
          <RadioGroup>
            <Radio value={1}>是</Radio>
            <Radio value={2}>否</Radio>
          </RadioGroup>,
        )}
      </FormItem>,

      <FormItem key="introduce" {...this.formLayout} label="品牌介绍">
        {introduceList.length > 0 ? form.getFieldDecorator('introduce', {
          rules: [{ required: true, message: '请上传品牌介绍！' }],
          initialValue: values.introduce,
        })(
          (<Upload {...introduceProps} fileList={introduceList}>
            品牌介绍<Icon type="upload"/>上传
          </Upload>),
        ) : form.getFieldDecorator('introduce', {
          rules: [{ required: true, message: '请上传品牌介绍！' }],
          initialValue: values.introduce,
        })(
          (<Upload {...introduceProps} fileList={
            values.introduce ? [
              {
                name: values.introduce,
                uid: 1,
                url: values.introduce,
              },
            ] : []
          }>
            品牌介绍<Icon type="upload"/>上传
          </Upload>),
        )}
      </FormItem>,

      <FormItem key="remark" {...this.formLayout} label="描述">
        {form.getFieldDecorator('remark', {
          rules: [{ required: false, message: '请输入至少五个字符的规则描述！', min: 5 }],
          initialValue: values.remark,
        })(<TextArea rows={4} placeholder="请输入至少五个字符"/>)}
      </FormItem>,
    ];
  };
  onCancel = () => {
    const { handleUpdateModalVisible } = this.props;
    this.setState({
      logoList: [],
      iconList: [],
      introduceList: [],
    });
    handleUpdateModalVisible(false, []);
  };

  //弹窗
  render() {
    const { updateModalVisible, modalVisible } = this.props;

    //完成
    const handleNext = () => {
      const { form, values, handleUpdate, handleAdd, modalVisible } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        const formVals = { ...values, ...fieldsValue };

        if (modalVisible) {
          handleAdd(formVals);
        } else {
          handleUpdate(formVals);
        }
        this.setState({
          logoList: [],
          iconList: [],
          introduceList: [],
        });
      });
    };
    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title={modalVisible ? '新增品牌' : '修改品牌'}
        visible={updateModalVisible}
        onOk={handleNext}
        onCancel={() => this.onCancel()}
      >
        {this.renderContent()}
      </Modal>
    );
  }
}

export default UpdateForm;
